<?php

namespace Chap12Bundle\Controller;

use Chap12Bundle\Entity\Task;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;


class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        return $this->render('Chap12Bundle:Default:index.html.twig');
    }


    /**
     * @Route("/task/new", name="task_new")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function newAction(Request $request)
    {
        $task = new Task();
        $task->setTask("write a blog post");
        $task->setDuedate(new \DateTime('tomorrow'));

        $form = $this->createFormBuilder($task)
            ->setAction($this->generateUrl('task_new'))
            ->setMethod('POST')
            ->add('task', TextType::class, array('required'=>true, 'label'=>"Task Name", 'attr'=>array('maxlength'=>6)))
            ->add('dueDate', DateType::class, array('widget'=>'single_text', 'required'=>true, 'label'=>"Due Date"))
            ->add('save', SubmitType::class, array('label'=>'Create Task'))
            ->add('saveAndAdd', SubmitType::class, array('label'=>'Save & Add'))
            ->getForm();

        // validation groups
        //$form = $this->createFormBuilder($task, array('validation_groups' => array('registration')));


        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $nextAction = $form->get('saveAndAdd')->isClicked() ? 'task_new' : 'task_success';

            return $this->redirectToRoute($nextAction);
        }

        $assign = array(
            'form' => $form->createView()
        );

        return $this->render('Chap12Bundle:Default:new.html.twig', $assign);
    }


    /**
     * @Route("/success", name="task_success")
     * @return Response
     */
    public function taskSuccessAction()
    {
        return new Response('success!');
    }

}
